<template>
  <div class="department">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>组织机构选择</span>
        </div>
      </template>
      <t-table
        :table="contentTableDom.table"
        :columns="contentTableDom.table.columns"
        @radioChange="radioChange"
        :isShowPagination="false"
      />
      <template #footer><el-button type="primary" @click="handleEnter">进入</el-button></template>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
const mock = [
  {
    id: '1',
    orgEname: 'D150',
    orgCname: '运营管理部',
  },
  {
    id: '2',
    orgEname: 'D290',
    orgCname: '投决会及专委会',
  },
]

import { chooseDeptAfterLogin, queryUserPostsWithDept ,getUserPostDeptsApi} from '@/api/modules/user'
import { useUserStore } from '@/store/modules/user'
import { computed, onMounted, reactive, ref } from 'vue'
import TTable from '@/components/table/index.vue'
import { useMessage } from '@/hooks/message'
import router from '@/router'

const userStore = useUserStore()
const loginName = computed(() => userStore.loginName)
const deptment = computed(() => userStore.deptment)
const token = computed(() => userStore.token)

const selectedRows: any = ref(null)
const contentTableDom = reactive({
  table: {
    firstColumn: { type: 'radio', fixed: true },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      { prop: 'orgEname', label: '组织机构代码' },
      { prop: 'orgCname', label: '组织机构名称' },
    ],
  },
})

// 选择单选框
const radioChange = (val: any) => {
  selectedRows.value = val
}

const getDataList = async () => {
  let { success, data } = await getUserPostDeptsApi({ loginName: loginName.value })
  console.log(data,'data123456')
  if (success) {
    contentTableDom.table.data = data.length ? data : mock
    console.log(contentTableDom.table, '111')
  }
}

const chooseDept = (row: any) => {
  let params = {
    deptment: `${row.orgEname}/${row.orgCname}`,
    deptCode: row.orgEname,
    deptName: row.orgCname,
    token: token.value,
  }
  chooseDeptAfterLogin(params).then((res) => {
    const { success } = res
    if (success) {
      userStore.setUserState('deptment', row)
      router.push('/index')
    }
  })
}

const handleEnter = () => {
  if (selectedRows.value) {
    chooseDept(selectedRows.value)
    return
  }
  useMessage().wraning('请先选择部门')
}
onMounted(() => {
  if (deptment.value.code) {
    console.log(111)
    selectedRows.value = deptment.value
  }
  getDataList()
})
</script>

<style lang="less">
.department {
  padding: 12px;
  background-color: #f2f2f2;
  height: 100%;

  .el-card {
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-card__body {
      flex: 1;
      overflow: auto;
    }
    .el-card__footer {
      text-align: right;
    }
  }
}
</style>
